const express = require("express");
const { check, validationResult } = require('express-validator')

const { db, genid } = require("../db/DbUtils.js")
const { jwts } = require("../utils/JsonWebtoken.js")
const { checks } = require("../utils/Validator.js")
const { EPSTATE } = require("../config/state.json")

const router = express.Router();


router.post("/", checks.userRegister(), async (req, res) => {

    // 捕获验证错误 向前端疯狂报错
    let errors = validationResult(req)
    if (!errors.isEmpty()) {
        return res.status(422).json({ errors: errors.array() })
    }

    let { user_account, user_password, user_email } = req.body;
    let user_id = genid.NextId();

    const sql_register = "insert into `register`(`user_id`, `user_account`, `user_password`, `user_email`) values (?, ?, ?, ?)";
    let params = [user_id ,user_account, user_password, user_email];
    let { err, rows } = await db.async.query(sql_register, params)

    if (err === null) {
        res.send({
            code: 200,
            msg: "申请成功 请等待审核..."
        })
    } else {
        res.send({
            code: 500,
            msg: "注册失败"
        })
    }

})


module.exports = router
